﻿/**
 * 通用js方法封装处理
 */

// 日期格式化
export function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time, 10)
    } else if (typeof time === 'string') {
      time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time *= 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    if (result.length > 0 && value < 10) {
      value = `0${value}`
    }
    return value || 0
  })
  return time_str
}

// 表单重置
export function resetForm(refName) {
  if (this.$refs[refName]) {
    this.$refs[refName].resetFields();
  }
}

// 添加日期范围
export function addDateRange(params, dateRange, propName) {
  const search = params;
  search.params = typeof (search.params) === 'object' && search.params !== null && !Array.isArray(search.params) ? search.params : {};
  dateRange = Array.isArray(dateRange) ? dateRange : [];
  if (typeof (propName) === 'undefined') {
    [search.params.beginTime, search.params.endTime] = dateRange;
  } else {
    [search.params[`begin${propName}`], search.params[`end${propName}`]] = dateRange;
  }
  return search;
}

// 回显数据字典
export function selectDictLabel(datas, value) {
  if (value === undefined) {
    return "";
  }
  const actions = [];
  Object.keys(datas).some((key) => {
    if (datas[key].value === (`${value}`)) {
      actions.push(datas[key].label);
      return true;
    }
    return false
  })
  if (actions.length === 0) {
    actions.push(value);
  }
  return actions.join('');
}

// 回显数据字典（字符串数组）
export function selectDictLabels(datas, value, separator) {
  if (value === undefined) {
    return "";
  }
  const actions = [];
  const currentSeparator = undefined === separator ? "," : separator;
  const temp = value.split(currentSeparator);
  Object.keys(value.split(currentSeparator)).some((val) => {
    let match = false;
    Object.keys(datas).some((key) => {
      if (datas[key].value === (`${temp[val]}`)) {
        actions.push(datas[key].label + currentSeparator);
        match = true;
        return true;
      }
      return false;
    })
    if (!match) {
      actions.push(temp[val] + currentSeparator);
      return true;
    }
    return false;
  })
  return actions.join('').substring(0, actions.join('').length - 1);
}

// 字符串格式化(%s )
export function sprintf(str) {
  const args = [];
  let flag = true;
  let i = 1;
  str = str.replace(/%s/g, () => {
    i += 1;
    const arg = args[i];
    if (typeof arg === 'undefined') {
      flag = false;
      return '';
    }
    return arg;
  });
  return flag ? str : '';
}

// 转换字符串，undefined,null等转化为""
export function parseStrEmpty(str) {
  if (!str || str === "undefined" || str === "null") {
    return "";
  }
  return str;
}

// 数据合并
export function mergeRecursive(source, target) {
  Object.keys(target).forEach(p => {
    try {
      if (target[p].constructor === Object) {
        source[p] = mergeRecursive(source[p], target[p]);
      } else {
        source[p] = target[p];
      }
    } catch (e) {
      source[p] = target[p];
    }
  })
  return source;
}

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
export function handleTree(data, id, parentId, children) {
  const config = {
    id: id || 'id',
    parentId: parentId || 'parentId',
    childrenList: children || 'children'
  };

  const childrenListMap = {};
  const nodeIds = {};
  const tree = [];

  function adaptToChildrenList(o) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]];
    }
    if (o[config.childrenList]) {
      o[config.childrenList].forEach((c) => {
        adaptToChildrenList(c);
      })
    }
  }

  data.forEach((d) => {
    const parentId = d[config.parentId];
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = [];
    }
    nodeIds[d[config.id]] = d;
    childrenListMap[parentId].push(d);
  })
  data.forEach((d) => {
    const parentId = d[config.parentId];
    if (nodeIds[parentId] == null) {
      tree.push(d);
    }
  })
  tree.forEach((t) => {
    adaptToChildrenList(t);
  })
  return tree;
}


export function handleDisabledTree(data, id, parentId, children) {
  const config = {
    id: id || 'id',
    parentId: parentId || 'parentId',
    childrenList: children || 'children'
  };

  const childrenListMap = {};
  const nodeIds = {};
  const tree = [];

  function adaptToChildrenList(o) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]];
    }
    if (o[config.childrenList]) {
      o.disabled = true;
      o[config.childrenList].forEach((c) => {
        adaptToChildrenList(c);
      })
    }
  }

  data.forEach((d) => {
    const parentId = d[config.parentId];
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = [];
    }
    nodeIds[d[config.id]] = d;
    childrenListMap[parentId].push(d);
  })
  data.forEach((d) => {
    const parentId = d[config.parentId];
    if (nodeIds[parentId] == null) {
      tree.push(d);
    }
  })
  tree.forEach((t) => {
    adaptToChildrenList(t);
  })
  return tree;
}

/**
 * 参数处理
 * @param {*} params  参数
 */
export function tansParams(params) {
  let result = ''
  Object.keys(params).forEach((propName) => {
    const value = params[propName];
    const part = `${encodeURIComponent(propName)}=`;
    if (value !== null && typeof (value) !== "undefined" && value !== '') {
      if (typeof value === 'object') {
        // 剔除数组类型查询条件
        // if (!Array.isArray(value)) {
        //   Object.keys(value).forEach((key) => {
        //     if (value[key] !== null && typeof (value[key]) !== 'undefined') {
        //       const params = `${propName}[${key}]`;
        //       const subPart = `${encodeURIComponent(params)}=`;
        //       result += `${subPart + encodeURIComponent(value[key])}&`;
        //     }
        //   })
        // }
        Object.keys(value).forEach((key) => {
          if (value[key] !== null && typeof (value[key]) !== 'undefined') {
            const params = `${propName}[${key}]`;
            const subPart = `${encodeURIComponent(params)}=`;
            result += `${subPart + encodeURIComponent(value[key])}&`;
          }
        })

      } else {
        result += `${part + encodeURIComponent(value)}&`;
      }
    }
  })
  return result
}

export function tansParamsToObject(params) {
  Object.keys(params).forEach((propName) => {
    const value = params[propName];
    if (value !== null && typeof (value) !== "undefined" && value !== '') {
      // if (Array.isArray(value)) {
      //   delete params[propName]
      // }
    }else {
      delete params[propName]
    }
  })
  return params
}

// 验证是否为blob格式
export async function blobValidate(data) {
  try {
    const text = await data.text();
    JSON.parse(text);
    return false;
  } catch (error) {
    return true;
  }
}

// 获取身份证生日
export function getIdCardBirthday(idCard) {
  let birthday = "";
  if (idCard != null && idCard !== "") {
    if (idCard.length === 15) {
      birthday = `19${idCard.substr(6, 6)}`;
    } else if (idCard.length === 18) {
      birthday = idCard.substr(6, 8);
    }

    birthday = birthday.replace(/(.{4})(.{2})/, "$1-$2-");
  }

  return birthday;
}

// 获取身份证性别
export function getIdCardSex(idCard) {
  let sexStr = "0";
  if (parseInt(idCard.slice(-2, -1), 10) % 2 === 1) {
    sexStr = "1";
  } else {
    sexStr = "2";
  }
  return sexStr;
}

// 获取身份证年龄
export function getIdCardAge(idCard) {
  const len = (`${idCard}`).length;
  if (len === 0) {
    return 0;
  }
  if (len !== 15 && len !== 18) {
    // 身份证号码只能为15位或18位其它不合法
    return 0;
  }

  let strBirthday = "";
  if (len === 18) {
    // 处理18位的身份证号码从号码中得到生日和性别代码
    strBirthday =
      `${idCard.substr(6, 4)
      }/${
        idCard.substr(10, 2)
      }/${
        idCard.substr(12, 2)}`;
  }
  if (len === 15) {
    strBirthday =
      `19${
        idCard.substr(6, 2)
      }/${
        idCard.substr(8, 2)
      }/${
        idCard.substr(10, 2)}`;
  }
  // 时间字符串里，必须是“/”
  const birthDate = new Date(strBirthday);
  const nowDateTime = new Date();
  let age = nowDateTime.getFullYear() - birthDate.getFullYear();
  // 再考虑月、天的因素;.getMonth()获取的是从0开始的，这里进行比较，不需要加1
  if (
    nowDateTime.getMonth() < birthDate.getMonth() ||
    (nowDateTime.getMonth() === birthDate.getMonth() &&
      nowDateTime.getDate() < birthDate.getDate())
  ) {
    age -= 1;
  }
  return age;
}

export function handleQuery(base, data) {
  Object.keys(data).forEach(val => {
    if (!Number.isNaN(data[val]) && base[val] === null) { // 需要是数字且根也为数字 这里 null 代表 数字 才进行转换
      data[val] = Number(data[val])
    }
  })
  return data
}

export function handleTheme(val, dict) {
  if (dict) {
    const item = dict.find(item => item.value === val)
    if (item !== undefined) {
      return item.listClass;
    }
  }
  return 'primary'
}

export function hexToRgba(hex, opacity) {
  const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  hex = hex.replace(shorthandRegex, (m, r, g, b) => r + r + g + g + b + b);

  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  opacity = opacity >= 0 && opacity <= 1 ? Number(opacity) : 1;
  return result
    ? `rgba(${
      [parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16), opacity].join(
        ','
      )
    })`
    : hex;
}
